package com.wedo.mall.activity.payment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.e.library.activity.EActivity;
import com.e.library.http.EApi;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.wedo.mall.R;
import com.wedo.mall.activity.agent.AgentDetailActivity;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.entity.Agent;
import com.wedo.mall.entity.AgentDetail;
import com.wedo.mall.payment.Payment;
import com.wedo.mall.util.WUrl;
import com.wedo.mall.widget.PaymentView;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * 向商家支付
 * Created by lxy on 2017/6/25.
 */
public class PaymentActivity extends EActivity{

    public static void toPayment(EActivity activity,String id){
        Bundle bundle = new Bundle();
        bundle.putString(AgentDetailActivity.EXTRA_AGENT,id);
        activity.toActivity(PaymentActivity.class,bundle);
    }

    @BindView(R.id.iv_head) ImageView iv_head;
    @BindView(R.id.tv_shop) TextView tv_shop;
    @BindView(R.id.ll_number) LinearLayout ll_number;
    @BindView(R.id.btn_input) Button btn_input;
    @BindView(R.id.pv_payment) PaymentView pv_payment;
    private StringBuilder input = new StringBuilder();

    private Agent agent;
    private AgentDetail detail;

    private Payment payment;

    @Override
    protected int layout() {
        return R.layout.activity_payment;
    }

    @Override
    protected void onActivityCreated(Bundle state) {
        String id = getIntent().getStringExtra(AgentDetailActivity.EXTRA_AGENT);
        detail(id);

        payment = Payment.with(this).listener(new Payment.OnPayListener() {
            @Override
            public void successful() {
                onPaySuccessful();
            }
        });
    }

    private void detail(String id){
        loading();
        Observable<EResponse> observable = api().agentDetail(id);
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();
                display(response);
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }

        });
    }

    private void display(EResponse response){
        detail = response.object("list",AgentDetail.class);
        agent = detail.agentDetail;
        if(agent == null) {
            defaultFinish();
            return;
        }

        //String str = getResources().getString(R.string.payment_pay_for_agent);
        tv_shop.setText(agent.agent_name);
        Glide.with(this).load(WUrl.url(agent.logo)).error(R.drawable.place_holder_agent).placeholder(R.drawable.place_holder_agent).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_head);
    }

    @Override
    protected void onResume() {
        super.onResume();
        pv_payment.onResume();

    }

    @OnClick(R.id.btn_input)
    protected void onInputClick(){
        ll_number.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.tv_number0,R.id.tv_number1,R.id.tv_number2,R.id.tv_number3,
            R.id.tv_number4,R.id.tv_number5,R.id.tv_number6,R.id.tv_number7
            ,R.id.tv_number8,R.id.tv_number9,R.id.tv_number_dot})
    protected void onNumberClick(TextView tv){
        input.append(tv.getText().toString().trim());
        btn_input.setText(input.toString());
    }

    @OnClick(R.id.iv_delete)
    protected void onDeleteClick(){
        if (TextUtils.isEmpty(input)){
            return;
        }
        input.deleteCharAt(input.length()-1);
        btn_input.setText(input.toString());
    }

    @OnClick(R.id.iv_dismiss)
    protected void onDismissClick(){
        ll_number.setVisibility(View.GONE);
    }


    @OnClick(R.id.btn_pay)
    protected void onPayClick(){
        if (TextUtils.isEmpty(input)){
            return;
        }

        if (!WLogin.isLogged(this)){
            return;
        }

        if(!WLogin.isBinding(this)) {
            return;
        }

        String amount = input.toString();

        payment.amount(amount);
        ll_number.setVisibility(View.GONE);
        //payment.onPaySelected(pv_payment);

        if (pv_payment.iPay88()){
            payment.iPay88Scan(agent.id,amount);
        } else if(pv_payment.paypal()) {
            payment.paypal();
        }else if(pv_payment.balance()) {
            if(!pv_payment.balanceEnough(amount)) {
                toast(R.string.payment_no_enough);
            }else if (pv_payment.hasPassword()){
                payment.showPayPassword();
            }else {
                payment.showSetPassword(pv_payment);
            }
        }else {
            toast(R.string.payment_coming_soon);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        payment.onActivityResult(requestCode,resultCode,data);
    }

    /**支付成功后通知服务端*/
    private void onPaySuccessful(){
        loading();
        Map<String,String> params = new HashMap<>(2);
        params.put("agent_id",agent.id);
        params.put("money",input.toString());
        Observable<EResponse> observable = api().post(EApi.MONEY_SWEEP_TO_PAY,params);
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();

                Bundle bundle = new Bundle();
                bundle.putString("amount",input.toString());
                bundle.putParcelable("agent",agent);
                toActivity(PaymentSuccessActivity.class,bundle);
                defaultFinish();
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }
}
